# -*- coding: utf-8 -*-
import sys

sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json
from common.helper import Helper
import time
from threading import Thread


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "百年童惠保重大疾病保险"

    # 生产产品数据
    def genProductInfo(self):

        plan = {

            "planA": {  # 年龄段
                "year": [str(i) for i in range(0, 18)],
                # 性别
                "gender": ["M", "F"],
                # 保障期限
                "expire": ["20年"],
                # 交费期间
                "interval": ["0", "5", "10"],
                # 保障金额
                "money": ["100000", "200000", "500000", "700000", "800000"],
                # 轻症疾病豁免 0 不投保 1 投保
                "slightDisease": ["0", "1"],
                # 投保人豁免责任 0 不投保 1 投保
                "personRes": ["0"]
            },
            "planB": {  # 年龄段
                "year": [str(i) for i in range(0, 18)],
                # 性别
                "gender": ["M", "F"],
                # 保障期限
                "expire": ["30年"],
                # 交费期间
                "interval": ["0", "5", "10", "20"],
                # 保障金额
                "money": ["100000", "200000", "500000", "700000", "800000"],
                # 轻症疾病豁免 0 不投保 1 投保
                "slightDisease": ["0", "1"],
                # 投保人豁免责任 0 不投保 1 投保
                "personRes": ["0"]
            },
            "planC": {  # 年龄段
                "year": [str(i) for i in range(0, 18)],
                # 性别
                "gender": ["M", "F"],
                # 保障期限
                "expire": ["50岁", "60岁"],
                # 交费期间
                "interval": ["0", "5", "10", "20", "30"],
                # 保障金额
                "money": ["100000", "200000", "500000", "700000", "800000"],
                # 轻症疾病豁免 0 不投保 1 投保
                "slightDisease": ["0", "1"],
                # 投保人豁免责任 0 不投保 1 投保
                "personRes": ["0"]
            }

        }
        for k in plan:
            for v in product(plan[k]["year"], plan[k]["gender"], plan[k]["expire"], plan[k]["interval"],
                             plan[k]["money"],
                             plan[k]["slightDisease"], plan[k]["personRes"]):
                if v[3] == "0":
                    payType = "一次交清"
                else:
                    payType = "年交"
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(
                    v[0], v[1], v[2], v[3], v[4], v[5], v[6], payType
                ))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(
                    v[0], v[1], v[2], v[3], v[4], v[5], v[6], payType
                ))

    # 执行爬虫
    def requestJson(self, dt=None,mysql=None):
        timestamps = int(time.time())

        if dt["slightDisease"] == "0":
            print("~~~~~~轻症不投~~~~~~~")
            if "岁" in dt["expire"]:
                Flag = "A"
            else:
                Flag = "Y"

            data = {
                "appntInfo": {"age": 32, "birthday": "1988-03-09", "ifSmoke": "N", "occupationCode": "3030101",
                              "sex": "M",
                              "socialSecurityFlag": "N"}, "cvalidate": "2020-3-10",
                "insuredInfo": {"age": dt["year"], "birthday": "{0}-01-01".format(str(2020 - int(dt["year"]))),
                                "ifSmoke": "N", "occupationCode": "3030101", "sex": dt["gender"],
                                "socialSecurityFlag": "N"}, "insuredRelationToAppnt": "CH", "policyInfoList": [
                    {"amnt": dt["money"], "dutyCode": "5307D1", "familyType": "", "getRate": "", "getYear": "",
                     "getYearFlag": "",
                     "insuredYear": dt["expire"].replace("年", "") if "岁" not in dt["expire"] else dt["expire"].replace(
                         "岁",
                         ""),
                     "insuredYearFlag": Flag, "mult": 1,
                     "payEndYear": "1000" if dt["interval"] == "0" else dt["interval"],
                     "payEndYearFlag": "Y", "payIntv": "0" if dt["payType"] != "年交" else "12", "prem": "223",
                     "renewalFlag": "NC", "riskCode": "5307",
                     "getLimit": "", "cvalidate": "2020-3-10"}], "saleChnl": "O"}
            payload = json.dumps(data)

            r = requests.post(url=domain[self.name]["url"] + str(timestamps), headers=domain[self.name]["header"],
                              data=payload)


            if r.status_code == 200 and r.json()["success"] == "true":
                price = Helper.decimalParse(r.json()["data"]["paCalResultList"][0]["prem"])
                data = {
                    "name": self.name,
                    "id": dt["id"],
                    "price": price
                }
                mysql.updatePrice(data)
            else:
                data = {
                    "name": self.name,
                    "id": dt["id"],
                    "state": 3
                }
                mysql.updateTask(data)
                print("\n/*更新产品价格失败:%d*/" % dt["id"])
        else:
            print("~~~~~轻症投保~~~~~")
            if "岁" in dt["expire"]:
                Flag = "A"
            else:
                Flag = "Y"
            data = {"appntInfo": {"age": 32, "birthday": "1988-03-09", "ifSmoke": "N", "occupationCode": "3030101",
                                  "sex": "M",
                                  "socialSecurityFlag": "N"}, "cvalidate": "2020-3-10",
                    "insuredInfo": {"age": dt["year"], "birthday": "{0}-01-01".format(str(2020 - int(dt["year"]))),
                                    "ifSmoke": "N", "occupationCode": "3030101", "sex": dt["gender"],
                                    "socialSecurityFlag": "N"}, "insuredRelationToAppnt": "CH", "policyInfoList": [
                    {"amnt": dt["money"], "dutyCode": "5307D1", "familyType": "", "getRate": "", "getYear": "",
                     "getYearFlag": "",
                     "insuredYear": dt["expire"].replace("年", "") if "岁" not in dt["expire"] else dt["expire"].replace(
                         "岁",
                         ""),
                     "insuredYearFlag": Flag, "mult": 1,
                     "payEndYear": "1000" if dt["interval"] == "0" else dt["interval"],
                     "payEndYearFlag": "Y", "payIntv": "0" if dt["payType"] != "年交" else "12", "prem": "223",
                     "renewalFlag": "NC", "riskCode": "5307",
                     "getLimit": "", "cvalidate": "2020-3-10"},
                    {"amnt": dt["money"], "dutyCode": "5307D2", "familyType": "", "getRate": "", "getYear": "",
                     "getYearFlag": "", "insuredYear": dt["expire"].replace("年","") if "岁" not in dt["expire"] else dt["expire"].replace("岁",""), "insuredYearFlag": Flag, "mult": 1, "payEndYear": "1000" if dt["interval"] == "0" else dt["interval"],
                     "payEndYearFlag": "Y", "payIntv": "0" if dt["payType"] != "年交" else "12", "prem": "", "renewalFlag": "NC", "riskCode": "5307",
                     "getLimit": ""}], "saleChnl": "O"}

            payload = json.dumps(data)

            r = requests.post(url=domain[self.name]["url"] + str(timestamps), headers=domain[self.name]["header"],
                              data=payload)

            if r.status_code == 200 and r.json()["success"] == "true":
                price = Helper.decimalParse(int(r.json()["data"]["paCalResultList"][0]["prem"]) + int(r.json()["data"]["paCalResultList"][1]["prem"]))
                data = {
                    "name":self.name,
                    "id":dt["id"],
                    "price":price
                }
                mysql.updatePrice( data )
            else:
                data = {
                    "name": self.name,
                    "id": dt["id"],
                    "state": 3
                }
                mysql.updateTask( data )
                print("\n/*更新产品价格失败:%d*/"%dt["id"])

    def main(self,mysql):

        while True:
            # 随机领取一条数据
            dt = mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

            # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            mysql.updateTask(data)

            self.requestJson(dt,mysql)
        # 多线程

    def startProcess(self):

        for i in range(5):

            mysql = MysqlClient()

            t = Thread(target=self.main, args=(mysql,))

            t.start()
